import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  workPlanListApi,
  workPlanStoreApi,
  workPlanUpdateApi,
  workPlanDeleteApi,
  workPlanCheckApi,
  workPlanFinishApi
} from "@/api/workPlanApi";
import dayjs from 'dayjs';
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    name: null,
    rangeTime: null,
    status: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "workPlanId",
      width: 60
    },
    {
      label: "创建人",
      prop: "createUser.name"
    },
    {
      label: "计划时间",
      prop: "planDate"
    },

    // {
    //   label: "工作状态",
    //   prop: "status",
    //   slot: "status",
    // },
    {
      label: "完成比例(%)",
      prop: "completeRate"
    },
    {
      label: "审核状态",
      prop: "statusStr"
    },
    {
      label: "附件",
      prop: "attachment",
      slot: "attachment"
    },
    // {
    //   label: "备注",
    //   prop: "remarks"
    // },



    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 260
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;

    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    let params = {
      page: form.page,
      perPage: form.perPage,
      name: form.name,
      planDate: form.rangeTime ? form.rangeTime : null,
      // startTime: form.rangeTime ? form.rangeTime[0] : null,
      // endTime: form.rangeTime ? form.rangeTime[1] : null,
      status: form.status
    }
    const res: any = await workPlanListApi(toRaw(params));
    dataList.value = res?.result.list;
    pagination.total = res?.result.total;
    pagination.pageSize = res?.result.perPage*1;
    pagination.currentPage = res?.result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    form.page = 1;
    form.name = null;
    form.rangeTime = null;
    form.status = null;
    formEl.resetFields();
    onSearch();
  };

  async function openDialog(title = "创建工作计划", row?: FormItemProps) {

    let formInline = {
      title: title,
      workPlanId: row?.workPlanId ?? null,
      workPlanTitle: row?.title ?? null,
      content: row?.content ?? null,
      attachment: row?.attachments ?? [],
      details: row?.details ?? [{content: ''}],
      planDate: row?.planDate ?? dayjs().format('YYYY-MM-DD'),
      status: 1,
      completeRate: row?.completeRate ?? 0,
      infoData: row ?? null,
      planHistory: null
    };
    if(title === "创建工作计划") {

    }
    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: title === '工作计划详情' || title === '完成工作计划'? '800px' : '600px',
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      hideFooter: title === '工作计划详情'? true : false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate((valid: any) => {
          if (valid) {

            let details = []
            for (let item of curData.details) {
              details.push(item.content)
            }
            let params = {
              workPlanId: curData.workPlanId,
              details: curData.details,
              planDate: curData.planDate,
              attachments: curData.attachment,
            }

            if (title === "创建工作计划") {
              workPlanStoreApi(toRaw(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }

              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else if(title === "编辑工作计划") {
              workPlanUpdateApi(params).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else if(title === "完成工作计划") {
              console.log(curData)
              let details = []
              for (let item of curData.details) {
                if(item.status === 0 && curData.completeRate === 100){
                  message("有未完成状态，完成比例不能为100%", {
                    type: "warning"
                  });
                  return
                }
                details.push({
                  workPlanDetailsId: item.workPlanDetailsId,
                  status: item.status,
                  completeRate: item.completeRate
                })
              }
              workPlanFinishApi({
                workPlanId: curData.workPlanId,
                completeRate: curData.completeRate,
                details: details
              }).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else if(title === "审核工作计划") {
              // if(curData.status === 3) {
              //   if(!curData.remarks) {
              //     message("请输入备注", {
              //       type: "warning"
              //     });
              //     return
              //   }
              // }
              workPlanCheckApi({
                workPlanId: curData.workPlanId,
                status: curData.status,
                remarks: curData.remarks,
              }).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row: any) {
    ElMessageBox.confirm('确定继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      workPlanDeleteApi({ workPlanId: row.workPlanId }).then((res: any) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
  };
}
